﻿import 'package:country_code_picker_plus/country_code_picker_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:vischat/core/utils/app_toast.dart';
import 'package:vischat/core/utils/jverify.dart';
import 'package:vischat/core/utils/phone_validator.dart';
import 'package:vischat/data/repositories/auth_repository.dart';
import 'package:vischat/generated/route_table.dart';

class LoginController extends GetxController {
  final AuthRepository _repo;
  LoginController(this._repo);

  final _textController = TextEditingController();
  final _focusNode = FocusNode();

  final _debounceIdentifier = ''.obs; // 防抖锁
  final _country = Rx<Country?>(null);
  final _phoneCheck = false.obs; // 手机号格式验证
  final _isAgree = false.obs; // 协议同意状态

  TextEditingController get textController => _textController;
  FocusNode get focusNode => _focusNode;
  bool get phoneCheck => _phoneCheck.value;
  bool get isAgree => _isAgree.value;

  void changeCountry(Country country) {
    _country.value = country;
  }

  void initCountry(Country? country) {
    _country.value = country;
  }

  // 手机号验证方法（带防抖）
  void validatePhoneNumber(String value) {
    _debounceIdentifier.value = value;
    debounce(_debounceIdentifier, (_) {
      _phoneCheck.value =
          _phoneCheck.value = PhoneNumberValidator.validatePhoneNumber(
            textController.text,
            _country.value?.code,
          );
    }, time: 300.milliseconds);
  }

  void toVerifySms() {
    if (!_isAgree.value) {
      AppToast.showToast('toast.agree'.tr);
      return;
    }
    focusNode.unfocus();
    JverifyUtil.getSMSCode(textController.text);
    Get.toNamed(
      RouteTable.LOGIN_VERIFYSMS,
      arguments: {"phone": textController.text},
    );
  }

  void handleAgree(bool? value) {
    _isAgree.value = value ?? false;
  }

  Future<void> handleOneClickLogin() async {
    final loginToken = await JverifyUtil.getToken();
    await _repo.login(loginType: LoginType.oneClick, loginToken: loginToken);
  }

  @override
  void onClose() {
    textController.dispose();
    super.onClose();
  }
}
